﻿using UnityEngine;

public class CameraShake : MonoBehaviour
{
    public static CameraShake Instance; // 单例模式，方便调用

    [Header("震动参数")]
    public float shakeDuration = 0.5f; // 震动持续时间
    public float shakeMagnitude = 0.2f; // 震动幅度
    public float dampingSpeed = 1.0f; // 震动衰减速度

    public Transform cameraTransform; // 摄像机的 Transform
    private Vector3 initialPosition; // 摄像机的初始位置
    private float currentShakeDuration = 0f; // 当前震动时间

    private void Awake()
    {
        // 初始化单例
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
        }

        // cameraTransform = Camera.main.transform; // 获取主摄像机
        initialPosition = cameraTransform.localPosition; // 保存初始位置
    }

    private void Update()
    {
        if (currentShakeDuration > 0)
        {
            // 生成随机偏移
            cameraTransform.localPosition = initialPosition + Random.insideUnitSphere * shakeMagnitude;

            // 减少震动时间
            currentShakeDuration -= Time.deltaTime * dampingSpeed;
        }
        else
        {
            // 恢复摄像机到初始位置
            currentShakeDuration = 0f;
            cameraTransform.localPosition = initialPosition;
        }
    }

    /// <summary>
    /// 开始震动
    /// </summary>
    /// <param name="duration">震动持续时间</param>
    /// <param name="magnitude">震动幅度</param>
    public void TriggerShake(float duration, float magnitude)
    {
        currentShakeDuration = duration;
        shakeMagnitude = magnitude;
    }
}